package com.mbc.web.common.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.uibinder.client.UiField;
import com.mbc.web.common.client.CommonControllerMgr;
import com.mbc.web.common.client.CommonMessage;
import com.mbc.web.common.client.ViewUtils;
import com.mbc.web.common.client.ui.control.MPasswordTextBox;
import com.mbc.web.common.client.ui.control.MButton;
import com.mbc.web.common.shared.HttpStatus;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;

public class FrmResetPassword extends Composite {

	private static FrmResetPasswordUiBinder uiBinder = GWT
			.create(FrmResetPasswordUiBinder.class);
	@UiField MPasswordTextBox txtOldPassword;
	@UiField MPasswordTextBox txtNewPassword;
	@UiField MPasswordTextBox txtConfirmPassword;
	@UiField MButton btnSave;

	interface FrmResetPasswordUiBinder extends
			UiBinder<Widget, FrmResetPassword> {
	}

	public FrmResetPassword() {
		initWidget(uiBinder.createAndBindUi(this));
		
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {
			
			@Override
			public void execute() {
				txtNewPassword.setFocus(true);
			}
		});
	}
	
	private boolean isValid(){
		ViewUtils.closeMessageBox();
		if(!ViewUtils.isValidate())
			return false;
		if(!txtNewPassword.getText().equals(txtConfirmPassword.getText())){
			ViewUtils.showErrorMessage("Password does not match.");
			txtNewPassword.setFocus(true);
			return false;
		}
		return true;
	}
	
	private AsyncCallback<Integer> actionCallback()
	{
		return new AsyncCallback<Integer>() {
			
			@Override
			public void onSuccess(Integer result) {
				ViewUtils.stopAjaxLoader();
				if(result == HttpStatus.OK){
					ViewUtils.showSuccessMessage(CommonMessage.saved_message);
					txtNewPassword.setText("");
					txtConfirmPassword.setText("");
					txtOldPassword.setText("");
				}
				else{
					if(result == HttpStatus.UNAUTHORIZED){
						ViewUtils.showErrorMessage("Old password does not match with existing one.");
						txtOldPassword.setFocus(true);
					} else if(result == HttpStatus.INTERNAL_SERVER_ERROR){
						ViewUtils.showErrorMessage(CommonMessage.internal_server_error_message);
					}
				}
			}
			
			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}
		};
	}

	@UiHandler("btnSave")
	void onBtnSaveClick(ClickEvent event) {
		if(isValid()){
			ViewUtils.startAjaxLoader(CommonMessage.saving_message);
			CommonControllerMgr.resetLoginPassword(txtOldPassword.getText(), txtNewPassword.getText(), actionCallback());
		}
	}
}
